package controller

import (
	"context"
	"fileNest/dao"
	"fileNest/global"
	"fileNest/model"
	"fileNest/util"
	"fmt"

	"github.com/gin-gonic/gin"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"golang.org/x/sys/windows"
)

// 天气
func Weather(ctx *gin.Context) {

}

// 储存占用
func Storage(ctx *gin.Context) {
	tokenString := ctx.GetHeader("Authorization")
	_, userID, err := util.ParseJWT(tokenString)
	if err != nil {
		util.FailResponse(ctx, fmt.Errorf("token验证失败"), 401)
		return
	}
	// var stat syscall.Statfs_t
	// path := "/"
	// err := syscall.Statfs(path, &stat)
	// if err != nil {
	// 	panic(err)
	// }

	// total := stat.Blocks * uint64(stat.Bsize) // 总大小
	// free := stat.Bfree * uint64(stat.Bsize)   // 可用大小
	// used := total - free                      // 已用大小

	path := "C:\\"

	var result = model.StorageType{}
	err = windows.GetDiskFreeSpaceEx(
		windows.StringToUTF16Ptr(path),
		&result.FreeBytesAvailable,
		&result.TotalNumberOfBytes,
		&result.TotalNumberOfFreeBytes,
	)
	if err != nil {
		util.FailResponse(ctx, err)
		return
	}
	pipeline := mongo.Pipeline{
		bson.D{
			bson.E{
				Key: "$match", Value: bson.M{
					"user_id": userID,
				},
			},
		},
		bson.D{
			bson.E{
				Key: "$group", Value: bson.M{
					"_id": nil,
					"totalSize": bson.M{
						"$sum": "$size",
					},
				},
			},
		},
	}

	cursor, err := global.DB.Collection("entries").Aggregate(context.Background(), pipeline)
	if err != nil {
		util.FailResponse(ctx, err)
		return
	}
	defer cursor.Close(context.Background())

	var total bson.M
	if cursor.Next(context.Background()) {
		if err := cursor.Decode(&total); err != nil {
			util.FailResponse(ctx, err)
			return
		}
	}
	if total["totalSize"] != nil {
		result.UserOfBytes = uint64(total["totalSize"].(int64))
	}

	result.OtherUserOfBytes = result.TotalNumberOfBytes - result.UserOfBytes - result.TotalNumberOfFreeBytes
	util.SuccessResponse(ctx, result)
}

// 最近上传
func RecentUploads(ctx *gin.Context) {
	tokenString := ctx.GetHeader("Authorization")
	_, userID, err := util.ParseJWT(tokenString)
	if err != nil {
		util.FailResponse(ctx, fmt.Errorf("token验证失败"), 401)
		return
	}
	var filter = bson.M{
		"user_id": userID,
	}
	var result model.FileEntryList
	findOptions := options.Find().SetSort(bson.M{"_id": -1}).SetSkip(0).SetLimit(10)

	if err := dao.DBFindMoreWithPage("entries", filter, findOptions, &result); err != nil {
		util.FailResponse(ctx, err)
		return
	}
	util.SuccessResponse(ctx, result)
}
